/**
 * 文件名：logger.ts
 * 作者：教务系统开发团队
 * 创建日期：2025-04-27
 * 描述：前端日志服务，用于记录请求、错误和用户操作日志
 */

import axios from 'axios';

/**
 * 日志级别常量
 */
const LogLevel = {
  DEBUG: 'DEBUG',
  INFO: 'INFO',
  WARN: 'WARN',
  ERROR: 'ERROR'
} as const;

type LogLevelType = typeof LogLevel[keyof typeof LogLevel];

/**
 * 日志服务类
 */
class Logger {
  private maxLogCount: number = 1000;
  private logStorageKey: string = 'jwxt_logs';
  private logCache: Array<{level: LogLevelType, message: string, timestamp: Date}> = [];
  private batchInterval: number = 5000;
  private batchTimer: NodeJS.Timeout | null = null;

  constructor() {
    this.setupInterceptors();
    this.initBatchTimer();
  }

  /**
   * 设置axios拦截器
   */
  private setupInterceptors() {
    // 请求拦截器
    axios.interceptors.request.use(
      config => {
        this.log(LogLevel.INFO, `请求发送: ${config.method?.toUpperCase()} ${config.url}`);
        return config;
      },
      error => {
        this.log(LogLevel.ERROR, `请求错误: ${error.message}`);
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    axios.interceptors.response.use(
      response => {
        this.log(LogLevel.INFO, `响应接收: ${response.status} ${response.config.url}`);
        return response;
      },
      error => {
        this.log(LogLevel.ERROR, `响应错误: ${error.message}`);
        return Promise.reject(error);
      }
    );
  }

  /**
   * 记录日志
   * @param level 日志级别
   * @param message 日志消息
   */
  public log(level: LogLevelType, message: string): void {
    const logEntry = {
      level,
      message,
      timestamp: new Date()
    };
    
    this.logCache.push(logEntry);
    
    // 控制日志缓存大小
    if (this.logCache.length > this.maxLogCount) {
      this.logCache.shift();
    }
  }

  /**
   * 初始化批量写入定时器
   */
  private initBatchTimer(): void {
    this.batchTimer = setInterval(() => {
      this.flushLogs();
    }, this.batchInterval);
  }

  /**
   * 批量写入日志到本地存储
   */
  private flushLogs(): void {
    if (this.logCache.length === 0) return;
    
    try {
      const existingLogs = JSON.parse(localStorage.getItem(this.logStorageKey) || '[]');
      const newLogs = [...existingLogs, ...this.logCache];
      
      // 控制存储的日志总量
      if (newLogs.length > this.maxLogCount * 2) {
        newLogs.splice(0, newLogs.length - this.maxLogCount);
      }
      
      localStorage.setItem(this.logStorageKey, JSON.stringify(newLogs));
      this.logCache = [];
    } catch (error) {
      console.error('日志存储失败:', error);
    }
  }

  /**
   * 销毁日志服务
   */
  public destroy(): void {
    if (this.batchTimer) {
      clearInterval(this.batchTimer);
      this.batchTimer = null;
    }
    this.flushLogs();
  }
}

const logger = new Logger();

export default logger;